
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using JYJ.AiYard.StationManagement.TbUser;
using JYJ.AiYard.StationManagement.TbUser.Dtos;
using JYJ.AiYard.StationManagement.TbUser.DomainService;
using JYJ.AiYard.StationManagement.TbUser.Authorization;
using Abp.Organizations;
using Abp.Authorization.Users;
using JYJ.AiYard.StationManagement.TbDeparts.DomainService;
using JYJ.AiYard.StationManagement.TbDeparts;
using JYJ.AiYard.Database;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbUser
{
    /// <summary>
    /// TbUser应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbUserAppService : AiYardAppServiceBase, ITbUserAppService
    {
        private readonly IRepository<TbUser, long> _entityRepository;

        private readonly IRepository<TbDepart, long> _entityDeptRepository;

        private readonly ITbUserManager _entityManager;

        private readonly ITbDepartManager _entityDeptManager;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;
        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbUserAppService(
        IRepository<TbUser, long> entityRepository,
        IRepository<TbDepart, long> entityDeptRepository,
        ITbUserManager entityManager,
        ITbDepartManager entityDeptManager,
        IAiYardDbTableIssuedCard aiYardDbTableIssuedCard
        )
        {
            _entityRepository = entityRepository;
            _entityDeptRepository = entityDeptRepository;
            _entityManager =entityManager;
            _entityDeptManager = entityDeptManager;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
        }


        /// <summary>
        /// 获取TbUser的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbUserPermissions.Query)] 
        public async Task<PagedResultDto<TbUserListDto>> GetPaged(GetTbUsersInput input)
		{
			List<long> StationList = new List<long>();
			tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
			if (filterText.StationId == null || filterText.StationId <= 0)
			{
				StationList = GetCurrenUserOrganizationAndChildrenUnit();
			}
			else
			{
				StationList.Add((long)filterText.StationId);
			}
			var query = _entityRepository.GetAll().Where(o => StationList.Contains(o.Station_ID));


            
            // TODO:根据传入的参数添加过滤条件

            if (!string.IsNullOrEmpty(input.FilterText))
                query = query.Where(o => o.User_Name.Contains(filterText.FilterText));

			var count = await query.CountAsync();

			var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();
            
			var entityListDtos =entityList.MapTo<List<TbUserListDto>>();

             

            return new PagedResultDto<TbUserListDto>(count,entityListDtos);
		}

        #region 获取当前组织代码的用户 
        /// <summary>
        /// 获取当前用户组织单元下的所有客户端信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<TbUserListDto>> GetAllUserToListDto(long StationId)
        {
            var tbDepart = await _entityRepository.GetAll().Where(o => o.Station_ID == StationId && o.IsDeleted==false)
                .OrderBy(o=> o.User_Name)
                .ToListAsync();

            var allTbDepart = tbDepart.MapTo<List<TbUserListDto>>();   

            return allTbDepart;
        }
        #endregion

        /// <summary>
        /// 通过指定id获取TbUserListDto信息
        /// </summary>
        [AbpAuthorize(TbUserPermissions.Query)] 
		public async Task<TbUserListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbUserListDto>();
		}

		/// <summary>
		/// 获取编辑 TbUser
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbUserPermissions.Create,TbUserPermissions.Edit)]
		public async Task<GetTbUserForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbUserForEditOutput();
            TbUserEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbUserEditDto>();
			}
			else
			{
				editDto = new TbUserEditDto();
			}

			output.TbUser = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbUser的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbUserPermissions.Create,TbUserPermissions.Edit)]
		public async Task CreateOrUpdate(CreateOrUpdateTbUserInput input)
		{
            if (input.TbUser.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            } 
            if (input.TbUser.Id.HasValue)
			{
				await Update(input.TbUser);
			}
			else
			{
				await Create(input.TbUser);
			}
		}


		/// <summary>
		/// 新增TbUser
		/// </summary>
		[AbpAuthorize(TbUserPermissions.Create)]
		protected virtual async Task<TbUserEditDto> Create(TbUserEditDto input)
		{
            //TODO:新增前的逻辑判断，是否允许新增 

            input.User_Opertion = Convert.ToInt32(AbpSession.UserId);
             
            var entity=input.MapTo<TbUser>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TbUserEditDto>();
		}

		/// <summary>
		/// 编辑TbUser
		/// </summary>
		[AbpAuthorize(TbUserPermissions.Edit)]
		protected virtual async Task Update(TbUserEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);
             
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除TbUser信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbUserPermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
            if (_aiYardDbTableIssuedCard.CheckIsForeignKey(input.Id, 0, "UserList"))
            {
                throw new Exception(input.Id + "存在外键约束，不允许删除");
            }
            //TODO:删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbUser的方法
		/// </summary>
		[AbpAuthorize(TbUserPermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
            foreach (long Id in input)
            {
                if (_aiYardDbTableIssuedCard.CheckIsForeignKey(Id, 0, "UserList"))
                {
                    throw new Exception(Id + "存在外键约束，不允许删除");
                }
            }
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		/// <summary>
		/// 导出TbUser为excel表,等待开发。
		/// </summary>
		/// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


